package com.gitee.chili.leisure.filter;

import com.gitee.chili.leisure.properties.FilterProperties;
import com.gitee.chili.leisure.util.GatewayUtil;
import com.gitee.chili.leisure.util.Utils;
import com.gitee.chili.leisure.util.encrypt.MD5Util;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class WebFilter extends ZuulFilter {

    @Autowired
    private FilterProperties properties;

    /**
     * 过滤器是否生效
     */
    @Override
    public boolean shouldFilter() {
        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String uri = request.getRequestURI();
        for (String u : properties.getFilterURI()) {
            if (uri.contains(u)) {
                return false;
            }
        }
        log.info("RequestMethod:{} , CorsFilter is true", request.getMethod());
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.getResponse().setContentType("application/json;charset=UTF-8");

        HttpServletResponse response = ctx.getResponse();
        HttpServletRequest request = ctx.getRequest();

        // 本地请求放行
        if (GatewayUtil.isLocalAddr(request)) {
            GatewayUtil.setHeader(request, response);
            return null;
        }

        GatewayUtil.startVerifySign();

        String token = request.getHeader("token");
        String timestamp = request.getHeader("timestamp");
        String sign = request.getHeader("sign");
        String method = request.getMethod();
        String contentType = request.getHeader("Content-Type");

        try {

            if (Utils.isEmpty(token, sign, timestamp) && GatewayUtil.isTimestamp(timestamp)) {
                GatewayUtil.endVerifySign(false);
                GatewayUtil.invalidRequest(ctx, "请求失败, 签名参数无效");
                return null;
            }

            String body = "";
            // 开始处理请求
            // 对post请求放行 & json格式
            if (Utils.nonEmpty(method, contentType)) {
                if (GatewayUtil.isJsonRequest(method, contentType)) {
                    body = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
                    if (log.isDebugEnabled()) {
                        log.debug("request body : {}", body);
                    }
                } else if (GatewayUtil.isFormRequest(method, contentType)) {
                    // TODO 表单处理
//                    return null;
                }
            }

            if (StringUtils.isEmpty(body)) {
                GatewayUtil.endVerifySign(false);
                GatewayUtil.invalidRequest(ctx, "请求无效");
                return null;
            } else {
                if (!properties.getWebSalt().equals(token)) {
                    GatewayUtil.endVerifySign(false);
                    GatewayUtil.invalidRequest(ctx, "token无效");
                    return null;
                } else {
                    //  验证token是否合法
                    String param = body + timestamp + properties.getWebSalt();
                    String localSign = MD5Util.encryption(param);
                    if (localSign.equals(sign)) {
                        log.info(" 接口验签通过，sign：{}", sign);
                        GatewayUtil.endVerifySign(true);
                    } else {
                        log.info(" localhost success sign: [ {} ]", localSign);
                        log.info(" http request body：{}", body);
                        log.info(" validate sign fail , sign:[ {} ] , timestamp: [ {} ]", sign, timestamp);
                        GatewayUtil.endVerifySign(false);
                        GatewayUtil.invalidRequest(ctx, "签名错误");
                    }
                }
            }

            GatewayUtil.setHeader(request, response);

        } catch (Exception e) {
            GatewayUtil.endVerifySign(false);
            log.error("token验证异常:{}", e.getMessage(), e);
            GatewayUtil.invalidRequest(ctx, "验签失败");
        }
        return null;
    }

    /**
     * filterType：返回一个字符串代表过滤器的类型，在zuul中定义了四种不同生命周期的过滤器类型，具体如下：
     * <p>
     * pre：可以在请求被路由之前调用
     * route：在路由请求时候被调用
     * post：在route和error过滤器之后被调用
     * error：处理请求时发生错误时被调用
     * <p>
     * 需要打印返回信息时，必须使用 "post"
     *
     * @return pre
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 5;
    }

}
